﻿//----------------------------------------------------------------
//CodeArt.
//
//文件描述:
//
//创 建 人: dreamnan@hotmail.com(Blog:http://www.cnblogs.com/dreamnan)
//创建日期: 2009-10-15
//
//修订记录: 
//
//----------------------------------------------------------------
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using Microsoft.SharePoint.Utilities;


namespace CodeArt.SharePoint.Fields
{
    using Microsoft.SharePoint.ApplicationPages;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;

    /// <summary>
    /// Lookup Field 属性编辑器
    /// </summary>
    public class LookupFieldEditor : UserControl, IFieldEditor
    {
        SPSiteLookupField _lookupField = null;

        protected DropDownList _webField = null;
        protected DropDownList _listField = null;
        protected DropDownList _mainDisplayColumnField = null;
        protected RadioButton _rdoLookup = null;
        protected RadioButton _rdoPickerDialog = null;

        bool IFieldEditor.DisplayAsNewSection
        {
            get { return false; }
        }

        void IFieldEditor.InitializeWithField(SPField field)
        {
            _lookupField = field as SPSiteLookupField;

            if (Page.IsPostBack)
            {
                return;
            }

            try
            {
                /*** Run first time initialization ***/
                // The drop down with webs in the current site 
                // collection is maintained with viewstate
                FillWebDropDown();
                // Get the selected list item for update scenario
                ListItem selectedWebListItem = null;
                if (_lookupField != null && _lookupField.LookupWebId != null)
                {
                    selectedWebListItem = _webField.Items.FindByValue(
                        _lookupField.LookupWebId.ToString());
                }

                if (_lookupField != null)
                {
                    if (_lookupField.AllowPickerDialog)
                        _rdoPickerDialog.Checked = true;
                    else
                        _rdoLookup.Checked = true;
                }
                else
                    _rdoLookup.Checked = true;

                // If unavailable select the current web
                if (selectedWebListItem == null)
                {
                    selectedWebListItem = _webField.Items.FindByValue(
                        SPContext.Current.Web.ID.ToString());
                }
                selectedWebListItem.Selected = true;
                // Fill the list drop down for the current web,
                // it has an empty item on top in create scenarios
                FillListDropDown(selectedWebListItem.Value);
                // Get the selected list item for update scenario, 
                // do not default to first list in selected list
                ListItem selectedListListItem = null;
                if (_lookupField != null && _lookupField.LookupList != null)
                {
                    selectedListListItem = _listField.Items.FindByValue(
                        _lookupField.LookupList);
                }
                if (selectedListListItem != null && selectedListListItem.Value!=string.Empty)
                {
                    selectedListListItem.Selected = true;
                    // Create the column list for update scenario
                    Guid webID = new Guid(selectedWebListItem.Value);
                    Guid listID = new Guid(selectedListListItem.Value);
                    using (SPWeb web = SPContext.Current.Site.OpenWeb(webID))
                    {
                        SPList list = web.Lists[listID];
                        FillMainDisplayColumnList(list);
                    }
                    // Update the selected columns
                    string mainDisplayColumn = _lookupField.LookupField;
                    ListItem mainDisplayColumnItem = _mainDisplayColumnField.Items.FindByValue(mainDisplayColumn);
                    if (mainDisplayColumnItem != null)
                    {
                        mainDisplayColumnItem.Selected = true;
                    }

                }

                if (field != null)
                {
                    _webField.Enabled = false;
                    _listField.Enabled = false;
                }
            }
            catch(Exception ex)
            {
                //throw;
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        void IFieldEditor.OnSaveChange(SPField field, bool isNewField)
        {
            SPSiteLookupField lookupField = (SPSiteLookupField)field;
            if (isNewField)
            {
                lookupField.LookupWebId = new Guid(_webField.SelectedValue);
                lookupField.LookupList = _listField.SelectedValue;
            }
            lookupField.LookupField = _mainDisplayColumnField.SelectedValue;
            
            if (_rdoPickerDialog.Checked)
                lookupField.AllowPickerDialog = true;
            else
                lookupField.AllowPickerDialog = false;
        }

        protected void WebField_SelectedIndexChanged(
            object sender, EventArgs e)
        {
            _listField.Items.Clear();
            _mainDisplayColumnField.Items.Clear();
            string selectedWebIDString = _webField.SelectedValue;
            if (String.IsNullOrEmpty(selectedWebIDString) == false)
            {
                FillListDropDown(selectedWebIDString);
            }
            Page.SetFocus(_listField);
        }

        protected void ListField_SelectedIndexChanged(
            object sender, EventArgs e)
        {
            _mainDisplayColumnField.Items.Clear();
            string selectedListIDString = _listField.SelectedValue;
            if (String.IsNullOrEmpty(selectedListIDString) == false)
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb(
                    new Guid(_webField.SelectedValue)))
                {
                    SPList list = web.Lists[new Guid(_listField.SelectedValue)];
                    FillMainDisplayColumnList(list);
                }
            }
            Page.SetFocus(_mainDisplayColumnField);
        }

        void FillWebDropDown()
        {
            _webField.Items.Add("");
            SPSite site = SPContext.Current.Site;
            foreach (SPWeb web in site.AllWebs)
            {
                using (web)
                {
                    ListItem webListItem = new ListItem();
                    webListItem.Text = web.Title;
                    webListItem.Value = web.ID.ToString();
                    _webField.Items.Add(webListItem);
                }
            }
        }

        void FillListDropDown(string webIDString)
        {
            _listField.Items.Add("");
            Guid webID = new Guid(webIDString);
            using (SPWeb web = SPContext.Current.Site.OpenWeb(webID))
            {
                foreach (SPList list in web.Lists)
                {
                    if (list.Hidden == false)
                    {
                        ListItem listListItem = new ListItem();
                        listListItem.Text = list.Title;
                        listListItem.Value = list.ID.ToString();
                        _listField.Items.Add(listListItem);
                    }
                }
            }
        }

        void FillMainDisplayColumnList(SPList list)
        {
            FillColumnList(list, _mainDisplayColumnField.Items);
        }

        void FillColumnList(SPList spList, ListItemCollection list)
        {
            foreach (SPField field in GetDisplayColumns(spList))
            {
                string title = String.Concat(
                    field.Title, " ", field.AuthoringInfo);
                ListItem listItem = new ListItem(title);
                listItem.Value = field.InternalName;
                list.Add(listItem);
            }
        }

        IEnumerable<SPField> GetDisplayColumns(SPList list)
        {
            foreach (SPField field in list.Fields)
            {
                //if (field.Hidden == false)
                if (!field.Hidden && field.Group != "_Hidden" &&
                    field.InternalName != "_UIVersionString" &&
                    field.InternalName != "LinkTitle" &&
                    field.InternalName != "LinkTitleNoMenu" &&
                    field.InternalName != "DocIcon" &&
                    field.InternalName != "Attachments" &&
                    field.InternalName != "Edit" &&
                    field.InternalName != "ID")
                {
                    switch (field.Type)
                    {
                        case SPFieldType.Calculated:
                            if (((SPFieldCalculated)field).OutputType == SPFieldType.Text)
                            {
                                yield return field;
                            }
                            break;
                        case SPFieldType.Computed:
                            if (((SPFieldComputed)field).EnableLookup)
                            {
                                yield return field;
                            }
                            break;
                        case SPFieldType.Counter:
                        case SPFieldType.Text:
                            yield return field;
                            break;
                    }
                }
            }
        }
    }
}
